class AdvertismentsController < ApplicationController

  def show
    @advertisment           = Advertisment.find(params[:id])
    @university             = @advertisment.university
    @user                   = @advertisment.user
    @similarads             = @advertisment.sub_category.advertisments.find(:all, :limit => 3)
    @advertisment_attribute = @advertisment.advertisment_attribute_field_value
    @category               = Category.find(SubCategory.find(@advertisment.sub_category_id).category_id).id

    unless @advertisment_attribute.nil?
      
      @field_values           = (@advertisment_attribute.field_values)
    end
    @images                 = @advertisment.attachments
    @firstimage             = @images.first
    @imagescount            = @images.length
  end

  def comments
    @advertisment           = Advertisment.find(params[:id])
    @comments               = @advertisment.comments(:order=>"created_at")
    render :layout => false
  end

  def full_image
    @advertisment           = Advertisment.find(params[:id])
    @images                 = @advertisment.attachments
    @firstimage             = (params[:imageid].nil? ? @images.first : Attachment.find(params[:imageid]))

    render :layout => false
  end

  def swap_image
    @advertisment           = Advertisment.find(params[:id])    
    @firstimage             = Attachment.find(params[:imageid])
    render :layout => false
  end
  
  def save_advertisment
    @advertisment           = Advertisment.find(params[:id])
    if session[:user]
       @user_id                = session[:user][:id]
       @bookmarks          = BookmarkedAd.find(:all, :conditions=>"user_id='"+@user_id.to_s+"'")
    end
    render :layout => false
  end

  def email_friend
    @advertisment           = Advertisment.find(params[:id])
######## changed here  ###############
if params[:youremail]!= "E-mail ID*" && params[:friendemail] != "Friend's E-mail ID*"  && params[:friendname] != "Friend's name*"  && params[:yourname] != "Your name*"
    @yourname   = params[:yourname]
    @friendname = params[:friendname]
    @youremail  = params[:youremail]
    @friendemail= params[:friendemail]
    if @youremail && @friendemail
      recipient = @friendemail
      message   = params[:message]+"Hi "+@friendname+" ! \n "+@yourname+" came across this ad and thinks you might find it useful"
      subject   = 'Ad suitable for you'
      Mailer.deliver_contact(recipient, subject, message)
    end


    if params[:friendname1] != "Friend's name*" && params[:friendemail1] =="Friend's E-mail ID*"
      @friendname1 = params[:friendname1]
      @friendemail1= params[:friendemail1]
      recipient = @friendemail1
      message   = params[:message]+"Hi "+@friendname1+" ! \n "+@yourname+" came across this ad and thinks you might find it useful"
      subject   = 'Ad suitable for you'
      Mailer.deliver_contact(recipient, subject, message)
    end
    
    if   params[:friendname2] != "Friend's name*" && params[:friendemail2] =="Friend's E-mail ID*"
      @friendname2 = params[:friendname2]
      @friendemail2= params[:friendemail2]
      recipient = @friendemail2
      message   = params[:message]+"Hi "+@friendname2+" ! \n "+@yourname+" came across this ad and thinks you might find it useful"
      subject   = 'Ad suitable for you'
      Mailer.deliver_contact(recipient, subject, message)
    end

    if   params[:friendname3] != "Friend's name*" && params[:friendemail3] =="Friend's E-mail ID*"
      @friendname3 = params[:friendname3]
      @friendemail3= params[:friendemail3]
      recipient = @friendemail3
      message   = params[:message]+"Hi "+@friendname3+" ! \n "+@yourname+" came across this ad and thinks you might find it useful"
      subject   = 'Ad suitable for you'
      Mailer.deliver_contact(recipient, subject, message)
    end

    if   params[:friendname4] != "Friend's name*" && @friendemail4 =="Friend's E-mail ID*"
      @friendname4 = params[:friendname4]
      @friendemail4= params[:friendemail4]
      recipient = @friendemail4
      message   = params[:message]+"Hi "+@friendname4+" ! \n "+@yourname+" came across this ad and thinks you might find it useful"
      subject   = 'Ad suitable for you'
      Mailer.deliver_contact(recipient, subject, message)
      return if request.xhr?
      render :text => 'Message sent successfully'
    end

  else
    flash[:message] = "please enter an email address"
  end
    render :layout => false
end

  def report_abuse
     @advertisment           = Advertisment.find(params[:id])
     unless session[:user].nil?
     @user_id                = session[:user][:id]
     end
     render :layout => false
  end

  def blame_ad

      @reason       = params[:reason]
      @youremail    = params[:youremail]
      @yourname     = params[:youremail]
      @message      = params[:message]
      Blame.create(:flagged_as => @reason, :advertisment_id => params[:id],:person_email=> @youremail,:message=>@message)
  #    Blame.save
       redirect_to :action=>"show", :id=>params[:id]
       flash[:message]="Abuse Reported Successfully"
  end

  def postcomment
   if request.post?
      @user = User.new(:full_name=>params[:comment][:full_name], :email=>params[:comment][:email])
      @user.save
      @comment = Comment.new(:content=>params[:comment][:content], :user_id=>@user.id, :advertisment_id=>params[:id])
      @comment.save
      flash[:message]="Comment Sent Successfully"
      redirect_to :action=>"show", :id=>params[:id]
   end
  end

  def bookmark_ad
    @user_id = session[:user][:id]
    @advertisment = Advertisment.find_by_id(params[:id])
    @folder = params[:bookmark][:folder]
    #@event_id = params[:event]

    if request.post?
      @bookmark = BookmarkedAd.new(:folder=>@folder,:user_id=>@user_id,:advertisment_id=>@advertisment.id)
      @bookmark.save
      redirect_to :action=>"show", :id=>params[:id]
      flash[:message]="Advertisment Saved Successfully"
    end
  end

  def user_edit
    @user = User.find(params[:user_id])
    render :update do |page|
      page.replace_html "user_field_#{params[:field_name].to_s}", :partial => "advertisments/user_field_item_edit", :locals => {:user => @user, :field_name => params[:field_name], :label => params[:label] }
    end
  end

  def user_update
    @user = User.find(params[:user_id])
    @user.update_attribute(params[:field_name], params[:user_field_value])
    render :update do |page|
      page.replace_html "user_field_#{params[:field_name].to_s}", :partial => "advertisments/user_field_item", :locals => {:user => @user, :field_name => params[:field_name], :label => params[:label] }
    end
  end
  def check_email
    @email             = User.count_by_sql("select count(*) from users where email='"+params[:email]+"'")
    if @email >0
      flash[:message]="<font color=#ff0000>Email already exists. Please use a different E-mail Id or request for password! </font>"
     session[:existing_user]="True"
     session[:existing_user_email]=params[:email]
    else
      flash[:message]="<font color=green>Email Address Available!</font>"
      session[:existing_user]="False"
    end
    render  :layout=>false
  end

    def pin_code
      @pincode_details            = Pincode.find_by_postalcode(params[:pincode])
    if @pincode_details.nil?
      flash[:message]="<font color=#ff0000>Wrong Pincode </font>"
    
    end
    render  :layout=>false
  end

  def post_free_ad

    @step = params[:step].to_i
    @step ||= 1

    if @step == 1
      @user_types = UserTypeCategoryMap.find(:all)
      render :layout=>"post", :action => "step_1" and return
    elsif @step == 2
      if params[:type]=="student"
         @university                 = University.find_by_name(params[:university])
         @student                    = Student.create(params[:student])
         @student.university_id      = @university.id
         @verification_code          = rand(9999999).to_s
         @student.verification_code     = @verification_code
         @sub_category               = SubCategory.find_by_stripped_name(params[:sub_category][:stripped_name])
         @student.save
         @email                      = @student.email
         @advertisment               = Advertisment.create
         @advertisment.user          = @student
         @advertisment.university    = @university
         @advertisment.sub_category  = @sub_category
         @advertisment.save
         @user                       = @student
         @user_email                 = @user.email

          @recipient = params[:student][:email]
          subject = "Verify Your Account"
          message =  @verification_code
          
        begin
          Mailer.deliver_mail(@recipient, subject, message)
          catch(Exception e)
        rescue Exception => e
          
        end

          require 'open-uri'
          require 'cgi'


         Kernel.open(CGI::unescape('http://SMSCube.AcubePro.com/SendSMS/pushsms.aspx?UserName=peyush.bansal@gmail.com&Password=cancel&SenderID=SMC&Mobile='+params[:student][:mobile_no].to_s+'&Text=Verification_Code_'+@verification_code.to_s))
        
     
       
        
      else
         @nonstudent                 = NonStudent.create(params[:nonstudent])
         @nonstudent.verification_code  = rand(9999999).to_s
         @nonstudent.save
         @sub_category               = SubCategory.find_by_stripped_name(params[:sub_category][:stripped_name])
         @advertisment               = Advertisment.new
         @advertisment.user          = @nonstudent
         @advertisment.sub_category  = @sub_category
         @advertisment.save
         @user                       = @nonstudent
      end
                  
     
     
      

      render :layout=>"post", :action => "step_2" and return
    elsif @step == 3
      @advertisment = Advertisment.find(params[:advertisment_record_id])
      @advertisment.advertisment_attribute_field_value = AdvertismentAttributeFieldValue.create(:field_values => params[:advertisment_attributes],:university_id=>params[:university_id],:category_id=>params[:category_id],:sub_category_id=>params[:sub_category_id])
      @advertisment.save
      @advertisment.update_attributes(params[:advertisment])
      @user = @advertisment.user

     
      unless params[:upload].nil?
        params[:upload].each do |key,value|
          unless(value.nil?)
            attachment              = Attachment.new
            attachment.file         = value
            attachment.advertisment = @advertisment
            attachment.save
          end
        end
      end

      render :layout=>"post", :action => "step_3" and return

    elsif @step == 4
      @user                          = User.find(params[:user_id])
      User.update(@user,:name=>params[:user][:name],:password=>params[:password] [:original],:user_interests=>params[:interests],:contact_by_phone=>params[:user][:contact_by_phone],:contact_by_email=>params[:user][:contact_by_email],:recieve_smc_mails=>params[:user][:recieve_smc_mails],:recieve_third_party_mails=>params[:user][:recieve_third_party_mails])
      render :layout=>"post", :action => "step_4" and return
    end

  end

  def resend_password
    render :layout=> "false"
          @recipient = params[:user][:email]
          user=User.find_by_email(@recipient)
          if user.nil?
            @sent_user="False"
          else
              username=user.name
              password=user.password
              subject = "SearchMyCampus Password"
              message =  "Username: "+username+ "Password: "+password
              begin
              Mailer.deliver_mail(@recipient, subject, message)
              catch(Exception e)
              rescue Exception => e

            end
            @sent_user="True"
       end
  end

  def verify_code
   render :layout=> "false"
     @user=User.find_by_email(params[:email])
     @user_email=params[:email]
     @verification_code=params[:verification_code]
    if @user.verification_code==params[:verification_code]
      User.update(@user.id,:status=>1)
    else
      flash[:notice] = "Incorrect Verification Code..."
    end
  end
end